/** @format */
const jwt = require('jsonwebtoken')
const { Base64 } = require('js-base64')
import { BaseDao } from '../../sdk'
import { JWT_DB } from '../../db'
import { APP_KEY, TARGET_APPKEY } from '../../constants'
import dayjs = require('dayjs')
import * as aesUtil from '../../utils/common/aesUtil'

function getKey(param, key) {
  return Base64.encode(`${key}-${param}-${key}`)
}

function jwt_sign(param, key) {
  const token = jwt.sign({ sign: param }, getKey(param, key), { expiresIn: 3600 })
  return `Bearer ${token}`
}

export async function sendQimenRequest(context,source:string, body, sellerId: string,shopId) {
  // const jwtdao: IBaseDao = new BaseDao(context, JWT_DB)
  // const jwtInfo: any = await jwtdao.findOne({ name: 'jwt' })
  const httpKey = 'UrugZaHXhJ0qjt7TXQzABLe6gAv83ufyLbBAs8KfIrlsdOPKWeSXb5LsOEQUMmIT2mBlPWObNkjuap4YmILezteY47nKnLXnHhd'

  const cloud = context.cloud
  // const description = {
  //   api_path: urlObj,
  //   method: 'POST',

  //   header: {
  //     Authorization: jwt_sign(context.openId, httpKey),
  //     appkey: APP_KEY,
  //     timestamp: dayjs().format(),
  //     'Auth-Id': context.openId,
  //     'X-B3-TraceId': context.data.traceId
  //   }
  // }
  console.log('加密前-----', body)
  const bizValue = aesUtil.encrypt(JSON.stringify(body), httpKey)
  console.log('加密后-----', bizValue)
  const data = {
    buyer: context.openId,
    seller: sellerId,
    messageId: context.data.traceId,
    shopId: +shopId,
    eventType: 2,
    targetAppkey: TARGET_APPKEY,
    bizValue,
    description: JSON.stringify({
      source,
    })
  }
  //调用奇门api
  let res = await cloud.qimenApi.invoke({
    api: 'qimen.taobao.miniapp.crm.connect',
    data,
    autoSession: true
  })

  console.log('qimenres-----', res)
  if (res?.response?.success) {
    return res?.response
  }
  return {
    success: false,
    errorMessage: res?.response?.code,
    errorCode: JSON.stringify(res)
  }
}
